'use strict'

class task {
    constructor() {
        this.param = '/'
    }
    //创建资源
    async post(c) {
        var openid = c.box.user.openid;
        var task_id = c.body.task_id;
        try {
            let sqltext1 = `SELECT task_coin `
                + `FROM task `
                + `WHERE task_id = ${task_id}`
            var r1 = await c.service.psql.query(sqltext1);
            if (r1.rowCount === 0) {
                return c.status(404).send('task not found')
            }

            r1 = JSON.stringify(r1.rows).match(/\d+/g)[0];

            let sqltext2 = "SELECT user_coin FROM users WHERE openid = " + `'${openid}'`;
            var r2 = await c.service.psql.query(sqltext2);
            if (r2.rowCount === 0) {
                return c.status(404).send('user not found')
            }

            r2 = JSON.stringify(r2.rows).match(/\d+/g)[0];

            var now_coin = parseInt(r1) + parseInt(r2);
            let sqltext3 = "UPDATE users SET user_coin ="
                + `${now_coin}`
                + "where openid = "
                + `'${openid}'`;
            let r3 = await c.service.psql.query(sqltext3);
            return c.send('success');
        } catch (err) {
            console.log(err);
        }
    }
}

module.exports = task